/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 * */

// AmzServer - Tototoy's server model.
// Author: tonyjobmails@gmail.com (tonyhack).
//
// Define class SerialNumberPool.
//
// SerialNumberPool is a ordering serial number distribution pool. It use to distribute
// UDP serial number in the sending and receiving terminal. It is a cycling structure,
// and it supports the algorithm - "odd/even compare", this algorithm uses to distinguish
// the redundant resending udp pakcet which is caused by the acknowledgement packet's
// losing.
//

#ifndef __SERIAL__NUMBER__POOL__H
#define __SERIAL__NUMBER__POOL__H

#include "common.h"

namespace amz {

template <typename Type>
class SerialNumberPool {
 public:
  explicit SerialNumberPool(uint32 size) : pointer_(0),
         even_order_(true) {
    this->pool_ = new Type[size];
	if(this->pool_ == NULL) {
	  LOG(ERROR) << "Not enough memory for SerialNumberPool";
	} else {
      this->size_ = size;
    }
  }
  ~SerialNumberPool() {
    delete [] this->pool_;
  }

  // Size of pool
  inline uint32 GetSize() const { return size_; }
  // Get current location.
  inline uint32 GetCurrentLocation() const { return this->pointer_; }

  // Backward current location one step.
  inline void ShiftBackward() {
    ++this->pointer_;
    if(this->pointer_ >= this->size_) {
      this->pointer_ = 0;
      even_order_ = !even_order_;
    }
  }
  // Get element at current location.
  inline void Get(Type &element) const { element = this->pool_[this->pointer_]; }
   // Set element at current location.
  inline void Set(const Type &element) {
    this->pool_[this->pointer_] = element;
  }

  // Random access
  inline bool RandomGet(uint32 index, Type &element) const {
    if(index >= this->GetSize()) return false;
    element = this->pool_[index];
    return true;
  }
  inline bool RandomSet(uint32 index, const Type &element) {
    if(index >= this->GetSize()) return false;
    this->pool_[index] = element;
    return true;
  }

  // Check the loop is Even times.
  inline bool CheckEvenLoop() const { return this->even_order_; }

 private:
  Type *pool_;
  uint32 size_;
  uint32 pointer_;
  bool even_order_;
};

}  // namespace amz

#endif  // __SERIAL__NUMBER__POOL__H

